# coding=utf-8
import json

import requests


class DouBan(object):
    def __init__(self):
        self.url_temp = "https://m.douban.com/rexxar/api/v2/subject_collection/movie_showing/items?start={}&count=8&loc_id=108288"
        self.headers = {
            "Referer": "https://m.douban.com/movie/",
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"
        }

    def parse_url(self, url):
        resp = requests.get(url, headers=self.headers)
        json_str = resp.content.decode()
        return json_str

    def get_content_list(self, json_str):
        data_dict = json.loads(json_str)
        return data_dict["subject_collection_items"]

    def save_content_list(self, content_list):
        with open("douban.txt", "w", encoding="utf-8") as f:
            for content in content_list:
                f.write(json.dumps(content, ensure_ascii=False))
                f.write("\n")

    def run(self):
        num = 0
        while True:
            # start_url
            next_url = self.url_temp.format(num)

            # 发送请求，获取数据
            json_str = self.parse_url(next_url)

            # 提取数据
            content_list = self.get_content_list(json_str)

            # 保存
            self.save_content_list(content_list)

            num += 8

            if len(content_list) < 8:
                break


if __name__ == '__main__':
    douban = DouBan()
    douban.run()


